package com.everwin.web.utils;

import com.everwin.web.domain.DownloadFileDesc;
import org.springframework.http.MediaType;

public class DownloadUtil {

    public static DownloadFileDesc getDownloadFileDesc(String id){
        DownloadFileDesc downloadFileDesc = new DownloadFileDesc();
        int pointIndex = id.lastIndexOf(".");
        if(pointIndex <= 0) {
            downloadFileDesc.setHash(id);
            return downloadFileDesc;
        }
        String hash = id.substring(0,pointIndex);
        String suffix = id.substring(pointIndex+1);
        MediaType mediaType = getMediaType(suffix);
        if(mediaType== null) return downloadFileDesc;
        downloadFileDesc.setHash(hash);
        downloadFileDesc.setSuffix(suffix);
        downloadFileDesc.setMediaType(mediaType);
        downloadFileDesc.setDownload(false);
        return downloadFileDesc;
    }

    private static MediaType getMediaType(String suffix){
        switch (suffix){
            case "pdf":
                return MediaType.APPLICATION_PDF;
            case "jpg":
            case "jpeg":
                return MediaType.IMAGE_JPEG;
            case "png":
                return MediaType.IMAGE_PNG;
            case "json":
                return MediaType.APPLICATION_JSON;
            case "gif":
                return MediaType.IMAGE_GIF;
            default: return null;

        }
    }
}
